<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Model\Admin\Admin;
use App\Model\Coupon;
use App\Model\CouponRecord;
use App\Model\Distributors;
use App\Model\Feedback;
use App\Model\Order;
use App\Model\User;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Phper666\JWTAuth\JWT;
use App\Services\Wechat;
use App\Controller\AbstractController;


class CouponController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;
    protected JWT $jwt;
    protected Wechat $wechat;

    #[Inject]
    protected Coupon $coupon;

    #[Inject]
    protected CouponRecord $couponRecord;
    #[Inject]
    protected Admin $admin;

    public function __construct()
    {
        $this->jwt = container()->get(JWT::class);
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);

    }

    /**获取领取记录
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getRecordList(RequestInterface $request): ResponseInterface
    {
//        try {
        $page = $request->inputs(['page', 'limit', 'coupon_id', 'status']);
        $query = $this->couponRecord->where(function ($query) use ($page) {
            if ($page['coupon_id'] != '') {
                $query->where('coupon_id', $page['coupon_id']);
            }
            if ($page['status'] == 1) {
                $time = date('Y-m-d H:i:s', time());
                $query->where('expires_at', '>', $time);
                $query->whereNull('used_at');
            } elseif ($page['status'] == 2) {
                $query->whereNotNull('used_at');
            } elseif ($page['status'] == 3) {
                $time = date('Y-m-d H:i:s', time());
                $query->where('expires_at', '<=', $time);
                $query->whereNull('used_at');
            }
        });
        $data['total'] = $query->count();
        $data['list'] = $query->orderBy('id', 'desc')
        ->offset(($page['page'] - 1) * $page['limit'])
        ->limit($page['limit'])
        ->get()->toArray();

        foreach ($data['list'] as $k => &$v) {
            $v['nickname'] = User::where('id', $v['user_id'])->value('nickname');
            if ($v['used_at']) {
                $v['status'] = 2;
            } else {
                $now = time();
                $expire_time = strtotime($v['expires_at']);
                if ($now > $expire_time) {
                    $v['status'] = 3;
                } else {
                    $v['status'] = 1;
                }
            }
        }
        return $this->success($data);
    }

    /**列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getList(RequestInterface $request): ResponseInterface
    {
        $info = $this->admin->getInfo($request);
        if (!$info) {
            return $this->error(1001,'请重新登录');
        }
        $page = $request->inputs(['page', 'limit', 'is_active', 'distributor_id', 'type']);
        if (!isset($page['distributor_id']) || !$page['distributor_id']) {
            if ($info['type'] == Admin::TYPE_USER) {
                $page['distributor_id'] = Distributors::query()
                    ->where('mobile', $info['mobile'])
                    ->value('id');
            }
        }
        $query = $this->coupon->where(function ($query) use ($page) {
            if ($page['distributor_id']) {
                $query->where('distributor_id', $page['distributor_id']);
            }
            if ($page['is_active'] != '') {
                $query->where('is_active', $page['is_active']);
            }
            if ($page['type']) {
                $query->where('type', $this->coupon::TYPE_MAP[$page['type']]);
            }
        });
        $data['total'] = $query->count();
        $data['list'] = $query->orderBy('id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->get()->toArray();
        foreach ($data['list'] as $k => $v) {
            $cacheKey = Coupon::COUPON_DEVICE_CACHE . $v['id'];
            $data['list'][$k]['stations'] = $this->redis->sMembers($cacheKey);
            $data['list'][$k]['distributor_name'] = Distributors::where('id', $v['distributor_id'])->value('name');
            if ($v['type'] == $this->coupon::TYPE_MAP[$this->coupon::TYPE_RECHARGE_RECEIVE]) {
                $cacheKey = Coupon::COUPON_MONEY_CACHE . $v['id'];
                $data['list'][$k]['moneys'] = $this->redis->hGetAll($cacheKey);
            } else {
                $data['list'][$k]['moneys'] = [];
            }
            if ($data['list'][$k]['images']) {
                $data['list'][$k]['images'] = json_decode($data['list'][$k]['images'], true);
            }
            $all_people = DB::table('coupon_records')
                ->where('coupon_id', $v['id'])
                ->select(DB::raw('COUNT(DISTINCT user_id) as count'))
                ->first();
            $data['list'][$k]['record_count'] = $all_people->count;
        }
        return $this->success($data);
    }


    /**添加营销活动
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request): ResponseInterface
    {
        $params = $request->inputs(['id', 'type',
            'start_date', 'end_date', 'fee', 'days',
            'quantity', 'is_active', 'content', 'images', 'stations',
            'moneys', 'distributor_id']);
        $info = $this->admin->getInfo($request);
        if (!isset($params['distributor_id']) || !$params['distributor_id']) {
            if ($info['type'] == Admin::TYPE_USER) {
                $params['distributor_id'] = Distributors::query()
                    ->where('mobile', $info['mobile'])
                    ->value('id');
            } else {
                return $this->error(1001, '请选择经销商');
            }
        }
        if (isset($params['stations']) && !is_array($params['stations'])) {
            $stations = json_decode($params['stations']);
            $stations = array_unique($stations);
        } else {
            if (!$params['stations']) {
                $stations = [];
            } else {
                $stations = $params['stations'];
            }
        }
        unset($params['stations']);
        if (array_key_exists('record_count', $params)) {
            unset($params['record_count']);
        }
        if (isset($params['moneys']) && !is_array($params['moneys'])) {
            $moneys = json_decode($params['moneys'], true);
        } else {
            if (!$params['moneys']) {
                $moneys = [];
            } else {
                $moneys = $params['moneys'];
            }
        }
        unset($params['moneys']);
        $type = $params['type'];
        if (is_array($params['images']) && $params['images']) {
            $params['images'] = json_encode($params['images']);
        } else {
            $params['images'] = null;
        }
        if (isset($params['id']) && $params['id']) {
            $this->coupon->where('id', $params['id'])->update($params);
            $active = $this->coupon->where('id', $params['id'])->first();
        } else {
            $active = Coupon::create($params);
        }
        if (!$active) {
            return $this->error('1003', '创建失败 请稍后重试');
        }
        $cacheKey = Coupon::COUPON_DEVICE_CACHE . $active->id;
        foreach ($stations as $k => $v) {
            $this->redis->sAdd($cacheKey, $v);
        }
        if ($type == Coupon::TYPE_MAP[Coupon::TYPE_RECHARGE_RECEIVE]) {
            $cacheKey = Coupon::COUPON_MONEY_CACHE . $active->id;
            foreach ($moneys as $k => $v) {
                $this->redis->hSet($cacheKey, (string)$k, $v);
            }
        }
        return $this->success(msg: '添加活动成功');
    }


    /**删除营销
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function del(RequestInterface $request): ResponseInterface
    {
        $couponId = $request->input('id', 0, 'int');
        $this->coupon->where('id', $couponId)
            ->delete();
        $deviceKey = Coupon::COUPON_DEVICE_CACHE . $couponId;
        $moneyKey = Coupon::COUPON_MONEY_CACHE . $couponId;
        $this->redis->del($deviceKey);
        $this->redis->del($moneyKey);
        return $this->success(msg: '删除活动成功');
    }


    public function changeStatus(RequestInterface $request): ResponseInterface
    {
        $status = $request->input('status', 0, 'int');
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(code: 1001, msg: '缺失参数id');
        }
        $model = $this->coupon->where('id', $id)->first();
        if ($status > 0) {
            $this->coupon->where('distributor_id', $model->distributor_id)
                ->where('type', $model->type)
                ->update(['is_active' => 0]);
        }
        $this->coupon->where('id', $id)->update(['is_active' => $status]);
        return $this->success(msg: '修改成功');
    }


}
